#include "Utils.h"

int agrandar_memoria (char** datos, int nuevo_tamanio) {
	char* ptr_aux;

	ptr_aux = (char*) realloc (*datos, sizeof(char) * nuevo_tamanio);
	if (ptr_aux == NULL) {
		free (*datos);
		return MEMORY_ERROR;
	}
	*datos = ptr_aux;

	return SUCCESS;
}

int leerlinea(FILE* file_in, char** linea) {
	size_t buffer = 0;
	int i = -1;
	int aux_c;
	*linea = NULL;

	do {
		i++;
		if (i == buffer){
			buffer+=BUFFER_STEP;
			if (agrandar_memoria (linea, buffer + 2)){
				return MEMORY_ERROR;
			}
		}
		aux_c = fgetc(file_in);
		if (aux_c == EOF) break;
		(*linea)[i] = (char) aux_c;

	} while ((*linea)[i] != '\n');

	if ((i == 0) && (aux_c == EOF)){
		free (*linea);
		return EOF;
	}

	(*linea)[++i] = 0;
	if (agrandar_memoria (linea, i + 1)){
		return MEMORY_ERROR;
	}

	return SUCCESS;
}
